// packagePay/pages/examine/index.js
import {
    getExamineList,
    batchApproval,
    getQueryCompanyPayPlatform,
    getExamineInfo,
    checkTotalMoneySumApi
} from '../../../api/pay'
import {
    getCompanyBalance
} from '../../../../api/app'
import user from '../../../../utils/user.js'
import {
    goAppList,
    dateFormat,
    toast
} from '../../../../utils/util'

const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        paymentAmountCap: '',
        ExcessPriceUpLength: '',
        filterUpToLimitIds: [],
        cueMsg: '',
        isExcessPriceUp: false,
        payPlanInfo: {},
        isup: false,
        currentType: 0,
        list: [],
        active: 0,
        total: 0,
        totalMoney: 0,
        today: '',
        month: '',
        waitTotal: 0,
        isBatch: false,
        isWholeBatch: true,
        selects: [],
        pageNum: 1,
        isSuper: 0, // 拿到是否是超管标识
        isAdmin: '', // 拿到是否是管理员标识,
        rechargeStatus: false,
        balance: 0, // 公司余额,
        balanceRemind: 0,
        totalPrice: 0,
        userId: '',
    },
    onCloseExcessPriceUp() {
        this.setData({
            isExcessPriceUp: false
        })
    },
    async onBreakExcessPrice() {
        await this.onCloseExcessPriceUp()
        await this.getQueryCompanyPayPlatformFn(this.data.filterUpToLimitIds)
    },
    onChangeType(e) {
        let i = e.currentTarget.dataset.i
        if (!this.data.payPlanInfo.isOpenAlipay && i === 2) {
            wx.showToast({
                title: '支付宝账户未开通',
                icon: 'none'
            })
            return
        }
        if (!this.data.payPlanInfo.isOpenWx && i === 1) {
            wx.showToast({
                title: '微信账户未开通',
                icon: 'none'
            })
            return
        }
        if (this.data.payPlanInfo.isHaveAdvance && i === 2) {
            wx.showToast({
                title: '预支单暂不支持支付宝',
                icon: 'none'
            })
            return
        }
        this.setData({
            currentType: i
        })
    },
    closepopup() {
        this.setData({
            isup: false,
            confirmText: ''
        })
    },
    onEndSubmit() {
        if (this.data.currentType !== 0) {
            if (this.data.currentType === 1 && (this.data.payPlanInfo.wxCanUseBalance - this.data.totalPrice) < user.balanceRemind && user.balanceRemind !== 0) {
                this.setData({
                    rechargeStatus: true
                })
                console.log('当前余额不足')
                return
            }
            if (this.data.currentType === 2 && (this.data.payPlanInfo.alpayCanUseBalance - this.data.totalPrice) < user.balanceRemind && user.balanceRemind !== 0) {
                this.setData({
                    rechargeStatus: true
                })
                console.log('当前余额不足')
                return
            }
            this.approval(1)
        } else {
            wx.showToast({
                title: '请选择支付方式',
                icon: 'none'
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        user.waitLogin().then(() => {
            this.setData({
                isSuper: user.isSuperAdmin,
                isAdmin: user.isAdmin
            })
            if (!user.hasOpenid || !user.isAttention)
                wx.showModal({
                    title: '提示',
                    content: '您还未关注公众号，关注公众号即可订阅审批消息，是否立即关注？',
                    confirmText: '去关注',
                    cancelText: '我已关注',
                    confirmColor: '#00d679',
                    cancelColor: '#ccc',
                    success: (res) => {
                        user.isAttention = true
                        if (res.confirm) {
                            // setAttention({
                            //     openId: user.openid,
                            //     mpOpenid: '1',
                            //     isAttention: 1
                            // })
                            goAppList([{
                                url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd5c6159f72a9705f&redirect_uri=https://front.51zidan.com/mini-auth/pay.html?' + encodeURIComponent('openid=' + user.openid) + '&response_type=code&scope=snsapi_base#wechat_redirect',
                                time: 3000
                            },
                            {
                                url: 'applet::/pages/web-view/web-view?path=' + encodeURIComponent('https://mp.weixin.qq.com/s/BRtIsq0krGPepJDFAVcVWQ'),
                                type: 'redirectTo'
                            }
                            ])
                            // wx.navigateTo({
                            //     url: '/pages/web-view/web-view?path=' + encodeURIComponent('https://mp.weixin.qq.com/s/BRtIsq0krGPepJDFAVcVWQ')
                            // })
                        }
                    }
                })
        })
    },
    async onShow() {
        this.data.selects = []
        if (this.data.active !== 0) {
            // 需要 进入详情在出来需要清除
            this.setData({
                list: [],
                pageNum: 1
            })
        }
        await user.reLogin()
        user.waitLogin().then(() => {
            this.data.today = dateFormat('YYYY-mm-dd', new Date()),
            this.data.month = this.data.month ? this.data.month : dateFormat('YYYY-mm', new Date())
            this.getExamineList()

            // 只开通支付宝不调用
            if (user.isOpenWechatPay) {
                getCompanyBalance({
                    companyId: user.companyId
                }).then(res => {
                    console.log(this.data.balanceRemind, 'balanceRemind')
                    this.setData({
                        balance: res.availableAmount,
                        balanceRemind: user.balanceRemind,
                        userId: user.userId,
                    }, () => {
                        console.log(this.data.balanceRemind, 'balanceRemind')
                    })
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.setData({
            today: dateFormat('YYYY-mm-dd', new Date()),
            month: dateFormat('YYYY-mm', new Date())
        })

    },
    onAllExamine() {
        wx.navigateTo({
            url: '/packagePay/pages/examine/all/all'
        })
    },
    getExamineList() {
        getExamineList({
            userId: user.userId,
            companyId: user.companyId,
            month: this.data.month,
            queryCode: this.data.active,
            pageNum: this.data.pageNum,
            pageSize: this.data.active ? 50 : 10000
        }).then(res => {
            res.list = res.list.map(item => {
                item.selected = false
                return item
            })

            if (this.data.active === 0) {
                this.setData({
                    waitTotal: res.list.length,
                    list: res.list,
                    total: res.total,
                    totalMoney: res.totalMoney,
                    hasNext: res.hasNextPage
                })
            } else {
                this.data.list.push(...res.list)
                this.setData({
                    list: this.data.list,
                    total: res.total,
                    totalMoney: res.totalMoney,
                    hasNext: res.hasNextPage
                })
            }
        })
    },
    next() {
        if (this.data.hasNext) {
            this.data.pageNum += 1
            this.getExamineList()
        }

    },
    wait() {
        this.setData({
            active: 0,
            pageNum: 1,
            isWholeBatch: true
        })
        this.getExamineList()
    },

    ready() {
        this.setData({
            active: 1,
            isBatch: false,
            pageNum: 1,
            list: [],
            isWholeBatch: false
        })
        this.getExamineList()
    },
    selectDate(event) {
        this.setData({
            month: event.detail.value,
            isBatch: false,
            pageNum: 1,
            list: [],
        })
        this.getExamineList()
    },
    goExamine(event) {
        wx.navigateTo({
            url: '/packagePay/pages/examine/detail/detail?id=' + event.currentTarget.dataset.id
        })
    },
    onBatch() {
        this.setData({
            isBatch: true
        })
    },
    onCancelBatch() {
        this.setData({
            isBatch: false
        })
        this.cancelSelectAll()
    },
    // 选中审批单
    onSelect(event) {
        const index = event.currentTarget.dataset.index
        const item = this.data.list[index]
        const selected = item.selected
        this.setData({
            ['list[' + index + '].selected']: !selected
        })
        if (!selected) {
            this.data.selects.push(index)
        } else {
            const indexof = this.data.selects.indexOf(index)
            this.data.selects.splice(indexof, 1)
        }
        this.setData({
            selects: this.data.selects
        })
        console.log(this.data.selects)
    },
    // 选中所有审批单
    onSelectAll() {
        if (this.data.selects.length) {
            this.cancelSelectAll()
        } else {
            this.selectAll()
        }

    },
    cancelSelectAll() {
        this.data.selects = []
        this.data.list = this.data.list.map(item => {
            item.selected = false
            return item
        })
        this.setData({
            selects: this.data.selects,
            list: this.data.list
        })
    },
    selectAll() {
        this.data.selects = []
        this.data.list = this.data.list.map((item, index) => {
            if (item.state !== 4) {
                return item
            }
            this.data.selects.push(index)
            item.selected = true
            return item
        })
        this.setData({
            selects: this.data.selects,
            list: this.data.list
        })
    },
    // 批量审批
    batchApproval() {
        if (this.data.selects.length === 0) {
            return
        }
        wx.showActionSheet({
            itemList: ['批量通过', '批量驳回']
        }).then(async (res) => {
            const isAgree = res.tapIndex + 1
            console.log(isAgree, 'isAgree')
            if (isAgree === 1) {
                if (this.data.balanceRemind !== 0) {
                    console.log(user.balanceRemind, this.data.list, 'list')
                    const selectedArr = this.data.list.filter(item => {
                        if (item.selected) {
                            return item
                        }
                    })
                    let totalPrice = 0 // 发薪总金额
                    selectedArr.forEach(item => {
                        totalPrice += item.totalMoney
                    })
                    this.setData({
                        totalPrice: totalPrice
                    })
                    // if ((this.data.balance - totalPrice) < user.balanceRemind) {
                    //     this.setData({
                    //         rechargeStatus: true
                    //     })
                    //     console.log('当前余额不足')
                    //     return
                    // }
                }
                const ids = []
                let checkArr = []
                const selectInfo = []
                this.data.selects.forEach(index => {
                    ids.push(this.data.list[index].id)
                    checkArr.push({
                        serveCompanyId: this.data.list[index].serveCompanyId,
                        totalMoney: this.data.list[index].totalMoney,
                    })
                    selectInfo.push(this.data.list[index])
                })
                console.log(this.data.selects, 'selectsselects')
                console.log(checkArr, 'agfsgdshg')
                console.log(selectInfo, 'gudsfyugsydsgyhui')
                let res = await checkTotalMoneySumApi({
                    checkTotalMoneySumParamList: checkArr
                })
                console.log(res, 'sdfhuiiuhsdghuigsuih')
                if (res.serveCompanyIds?.length > 0) {
                    let serveCompanyId = res.serveCompanyIds
                    let filterUpToLimitIdsarr = []
                    serveCompanyId.forEach(ele => {
                        selectInfo.forEach((item) => {
                            if (item.serveCompanyId !== ele) {
                                filterUpToLimitIdsarr.push(item.id)
                            }
                        })
                    })
                    this.setData({
                        ExcessPriceUpLength: res.serveCompanyIds?.length,
                        isExcessPriceUp: true,
                        cueMsg: res.cueMsg,
                        paymentAmountCap: res.paymentAmountCap,
                        filterUpToLimitIds: filterUpToLimitIdsarr
                    })
                    return
                }
                this.setData({
                    filterUpToLimitIds: ids
                })
                await this.getQueryCompanyPayPlatformFn(ids)
            } else {
                await this.approval(2)
            }
        })
    },
    getQueryCompanyPayPlatformFn(ids) {
        getQueryCompanyPayPlatform({
            ids: ids.join(',')
        }).then((res) => {
            this.setData({
                payPlanInfo: res
            })
            if (res.isLastSp) {
                this.setData({
                    isup: true
                })
            } else {
                this.approval(1)
            }
        })
    },
    approval(isAgree) {
        wx.navigateTo({
            url: '/pages/password/password?type=get',
            events: {
                submit: (password) => {
                    const ids = []
                    this.data.selects.forEach(index => {
                        ids.push(this.data.list[index].id)
                    })
                    batchApproval({
                        payAccountFlag: this.data.currentType === 1 ? '10001' : '20001',
                        ids: isAgree === 1 ? this.data.filterUpToLimitIds : ids,
                        params: {
                            isAgree: Number(isAgree),
                            auditContent: isAgree === 1 ? '同意' : '驳回',
                            password: password
                        }
                    }).then(res => {
                        this.data.filterUpToLimitIds = []
                        this.data.selects = []
                        app.alert(res, 'success').then(() => {
                            this.getExamineList()
                            this.setData({
                                isBatch: false,
                                isup: false
                            })
                        })
                    }).catch(rej => {
                        console.log(rej, 'rej审批失败')
                        console.log(rej.data.code, 'code')
                        console.log(rej.data.msg, 'msg')
                        if (rej.data.code == 500) {
                            setTimeout(() => {
                                console.log('调用啦弹窗前')
                                toast(rej.data.msg)
                                console.log('调用啦弹窗后')
                            }, 1500)
                        }
                    })
                }
            }
        })
    },
    // 取消充值弹窗
    onCancelRecharge() {
        this.setData({
            rechargeStatus: false
        })
    },
    // 确定去充值
    onDetermineRecharge() {
        console.log('确定去充值')
        wx.navigateTo({
            url: '/packagePay/pages/recharge/index/index',
        })
    },
    // 提醒老板充值
    onShareAppMessage() {
        return {
            title: '发薪余额不足',
            path: '/packagePay/pages/recharge/index/index',
            imageUrl: '/packagePay/assets/img/remind-recharge.png'
        }
    },
})